package com.andon.microcellsimulator.common.mqtt;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.andon.microcellsimulator.common.util.EncryptUtil;
import com.andon.microcellsimulator.model.GlobalBeanManager;

/**
 * Created by SunYongqiang on 2016/1/29.
 */
public class MQTTServiceManager {

    private static String mMQTTServerAddr;

    public static void init(String mqttAddr) {
        mMQTTServerAddr = mqttAddr;
    }

    /**
     * 启动mqtt服务
     * @param context
     * @param topicID       订阅主题ID,如果有多个主题的话,请用逗号分隔
     * @param mqttCallback  回调
     */
    public static synchronized void startMqttService(Context context, String topicID, MQTTCallback mqttCallback) {

        // 获取mqtt是否开启
        SharedPreferences sp = context.getSharedPreferences(MQTTService.TAG, Context.MODE_PRIVATE);
        boolean started = sp.getBoolean(MQTTService.PREF_STARTED, false);

        if (started) {
            MQTTService.actionStop(context);
        }

        // 设置mqtt参数
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(MQTTService.PREF_SERVER_ADDR, mMQTTServerAddr);
        editor.putString(MQTTService.PREF_DEVICE_ID, GlobalBeanManager.getGlobalBean().getDeviceID());
        editor.putString(MQTTService.PREF_PASSWORD, GlobalBeanManager.getGlobalBean().getAccessToken());
        editor.putString(MQTTService.PREF_TOPIC_ID, topicID);
        editor.commit();

        // 设置mqtt监听
        MQTTService.setMqttCallback(mqttCallback);

        // 启动mqtt服务
        MQTTService.actionStart(context);

    }

    /**
     * 停止mqtt服务
     * @param context
     */
    public static synchronized void stopMqttService(Context context) {

        // 获取mqtt是否开启
        if (context != null) {
            SharedPreferences sp = context.getSharedPreferences(MQTTService.TAG, Context.MODE_PRIVATE);
            boolean created = sp.getBoolean(MQTTService.PREF_CREATED, false);

            Log.d("MQTTService", "created = " + created);
            if (created) {
//                sp.edit().putBoolean(MQTTService.PREF_STARTED, false).commit();
                MQTTService.actionStop(context);
            }
        }

    }

}
